<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>编辑公告通知</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
    <meta name="renderer" content="webkit">
    <link href="${pageContext.request.contextPath}/static/css/common.css" rel="stylesheet">
    <link href="${pageContext.request.contextPath}/static/plugins/layer/skin/layer.css" rel="stylesheet">
    <link href="${pageContext.request.contextPath}/static/plugins/bootstrap-3.3.5/css/bootstrap.min.css"
          rel="stylesheet">
          <link href="${pageContext.request.contextPath}/static/plugins/select2-4.0.0/dist/css/select2.min.css" rel="stylesheet">
    <link href="${pageContext.request.contextPath}/static/plugins/font-awesome-4.3.0/css/font-awesome.min.css"
          rel="stylesheet">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/plugins/jquery.time/jquery.timepicker.min.css">
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/plugins/multiselect/jquery.multiselect.css" />
	<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/plugins/multiselect/jquery.multiselect.filter.css" />
	<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/plugins/multiselect/assets/style.css" />
	<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/plugins/multiselect/assets/prettify.css" />
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/js/jquery-ui.css" />
    
    <script type="text/javascript" charset="utf-8" src="${pageContext.request.contextPath}/static/plugins/ueditor/ueditor.config.js?date=2"></script>
    <script type="text/javascript" charset="utf-8" src="${pageContext.request.contextPath}/static/plugins/ueditor/ueditor.all.min.js?date=0112"> </script>
    <!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型，比如你在配置项目里配置的是英文，这里加载的中文，那最后就是中文-->
    <script type="text/javascript" charset="utf-8" src="${pageContext.request.contextPath}/static/plugins/ueditor/lang/zh-cn/zh-cn.js"></script>
    
    
  	<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery.js"></script>
    <script src="${pageContext.request.contextPath}/static/js/jquery-1.11.3.min.js"></script>
	<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-ui.min.js"></script>
    <script src="${pageContext.request.contextPath}/static/plugins/bootstrap-3.3.5/js/bootstrap.min.js"></script>
    <script src="/static/plugins/bootstrap-3.3.5/js/bootstrap.min.js"></script>
    <script src="${pageContext.request.contextPath}/static/plugins/layer/layer.js" type="text/javascript"></script>
	<script src="${pageContext.request.contextPath}/static/plugins/select2-4.0.0/dist/js/select2.min.js"></script>
	<script src="${pageContext.request.contextPath}/static/plugins/My97DatePicker/WdatePicker.js"
        type="text/javascript"></script>
	<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/global.js"></script>
	<script src="${pageContext.request.contextPath}/static/js/jquery.form.js" type="text/javascript"></script>
	<script src="${pageContext.request.contextPath}/static/js/common.js?date=2016-11-25"></script>
	<script type="text/javascript" src="${pageContext.request.contextPath}/static/plugins/multiselect/jquery.multiselect.js?date=0112"></script>
	<script type="text/javascript" src="${pageContext.request.contextPath}/static/plugins/multiselect/jquery.multiselect.filter.js"></script>
	<script type="text/javascript" src="${pageContext.request.contextPath}/static/plugins/multiselect/assets/prettify.js"></script>
    
	
    <style type="text/css">
	    .div1{
		    position: relative;
		    line-height: 35px;
		    height: 35px;
	    }
      .box4{
        	text-align: center;
		    font-size: 15px !important;
		    line-height: 28px;
		    -webkit-border-radius: 7px;
		    -moz-border-radius: 7px !important;
		    background: white;
		    color: black !important;
		    border: 1px solid #AFAAAA;
		    padding: 0 15px 0 15px;
        }
      .box5{
        	text-align: center;
		    font-size: 15px !important;
		    line-height: 28px;
		    -webkit-border-radius: 7px;
		    -moz-border-radius: 7px !important;
		    background: #cccccc;
		    color: black !important;
		    border: 1px solid #AFAAAA;
		    padding: 0 15px 0 15px;
        }
        #editDiv{
       		 margin-right: 20px;
        }
        #btns{
        	margin-top: 15px;
        	height: 30px;
        }
        #btns2{
        	margin-top: 15px;
        	height: 30px;
        	text-align: center;
        }
        #send1{
        	display: inline;
        	margin-right: 20%;
        }
        #send2{
        	display: inline;
        }
        #mTypeDiv{
        	margin-top: 15px;
        	height:300px;
        	text-align: center;
        }
        .finishdiv{
        	float: right;
        	margin-right: 20px;
        }
        
        
        .divDistribute{
        	height:300px;
    		overflow-y: auto;
    		width: 80%;
    		margin: 0 auto;
        }
        .border{
               border: 1px solid #eeeeee;
        }
       .tdborder{
               border: 1px solid #eeeeee;
               height: 32px;
               padding: 5px 8px 0px 8px !important;
               width: 15%;
               min-width:85px;
               text-align: left;
               color: #666;
    		   font-size: 14px;
        }
        .tdborder4{
               border: 1px solid #eeeeee;
               height: 32px;
               padding: 5px 8px 0px 8px !important;
               width: 15%;
               min-width:80px;
               text-align: left;
               color: #666;
    		   font-size: 14px;
        }
        .tdborder3{
               border: 1px solid #eeeeee;
               height: 32px;
               padding: 0px 8px 0px 8px !important;
               width: 30%;
               min-width:240px;
               text-align: left;
               color: #666;
    		   font-size: 14px;
        }
        .tdborder2{
               border: 1px solid #eeeeee;
               padding:0px !important;
               width: 40%;
        }
    </style>
</head>
<body view="menu-item-4142">
<jsp:include page="../../top.jsp"></jsp:include>
<div class="right">
    <div class="jqGrid_wrapper">
        <input type="hidden" name="acceptUserId" id="acceptUserId" />
        <input type="hidden" name="sid" value="${communityMsg.sid}">
        <div id="jqGrid_operation" class="div1">
            <div class="jqGrid_operation" id="action">
            	<div id="editDiv" >
            		<button name="edit" id="edit"  disabled class="box5" type="button"  onclick="setEnabled()">修改</button>
            	</div>
            </div>
        </div>
		<div >
			<div>
				<script id="editor" type="text/plain" style="height:400px;"></script>
			</div>
		</div>
		<div id="btns" >
		    <div class="finishdiv">
		        <button onclick="setDisabled()" id="finish" class="box4" >编辑完成</button>
		    </div>
		</div>
		<div id="btns2" style="display:none" >
		    <div id="send1" style="">
		        <button onclick="setSendAll()" id="sendAll" class="box5" >发送全部</button>
		    </div>
		    <div id="send2">
		        <button onclick="distribute()" id="sendSingle" class="box4" >发送个别</button>
		    </div>
		</div>
        <div class="" id="mTypeDiv" style="display:none">
            <div class="divDistribute" >
            	<table id="agtTable" class="table border">
            	</table>
            </div>
		</div>
		<div style="text-align: center;margin-top: 15px;margin-bottom: 15px;">
         <button class="btn btn-success form-control" id="sub" onclick="checkTail()" style="width: 150px;">发布</button>
         <button class="btn btn-success form-control" id="cancel" onclick="cancel()" style="width: 150px;">取消</button>
     	</div>
    </div>
</div>

<script>
	var range;
	if("${receiver}"=="*" || "${receiver}"==""){
		range=0;
		$("#acceptUserId").val("");
    	$("#mTypeDiv").attr("style","display:none");
	}else{
		range=1;
		$("#acceptUserId").val('${receiver}');
    	$("#mTypeDiv").attr("style","display:none");
	}
	
	var iffinish = false;
    $(function () {
    	 //实例化编辑器
        //建议使用工厂方法getEditor创建和引用编辑器实例，如果在某个闭包下引用该编辑器，直接调用UE.getEditor('editor')就能拿到相关的实例
        UE.getEditor('editor',{
            toolbars: [
                       ['fullscreen','undo', 'redo', 'bold', 'italic', 'indent', 'pasteplain', 'removeformat', 'formatmatch', 'time', 'date','fontsize', 'simpleupload', 'insertimage','justifyleft', 'justifyright', 'justifycenter','justifyjustify','selectall','cleardoc']
            ]}).addListener('ready', function (editor) {
			var value = '${msg}';
			UE.getEditor('editor').setContent(value);
		});

     	$.ajax({
             type: "POST",
             async: false,
             url: '/admin/auth_buttons.action',
             data: "url=" + window.location.pathname,
             success: function (data) {
                 data = eval("(" + data + ")");
                 for (var i in data) {
                     var action = data[i].mName;
                     switch (action) {
                         case "公告删除":
                         		$("#editDiv").prepend("<button name='delete' id='delete' class='box4' type='button' style='margin-right: 30px;'  onclick='deleteMsg(${communityMsg.sid})'>删除</button>");
                             break;
                     }
                 }
             }
     	});

     	
        $(".select2").select2({
            minimumResultsForSearch: -1,
            width:'100%'
        });

       
    });

    function setSendAll(){
    	range=0;
    	$("#sendAll").attr("disabled", "true");
    	$("#sendAll").attr("class", "box5");
    	$("#sendSingle").removeAttr("disabled");
    	$("#sendSingle").attr("class", "box4");
    	$("#mTypeDiv").attr("style","display:none");
    }
    
    var sids = ",";
    //点击部分小区后查询小区
    function distribute(){
    	range=1;
    	$("#sendAll").removeAttr("disabled");
    	$("#sendAll").attr("class", "box4");
    	$("#sendSingle").attr("disabled", "true");
    	$("#sendSingle").attr("class", "box5");
    	$("#mTypeDiv").attr("style","");
   		 var table=$("#agtTable");
		  table.empty();
		  $.post("${pageContext.request.contextPath}/admin/cinstallunit_listBudingAndUnit.action", function (data) {
			  var tr;
			  var td;
			  var td2;
			  var td3;
			  var td4;
			  var width2 = 0;
			  var width3 = 0;
	            for (var i = 0; i < data.length; i++) {
					sids += data[i].SID+","; 
		            var tr=$("<tr></tr>");
		   			tr.appendTo(table);
		   			var td=$("<td class=\"tdborder\">"+data[i].CBNAME+"<input id='comuAlluser"+data[i].SID+"' value='"+data[i].USERIDS+"' type=\"hidden\"/></td>");
		   			td.appendTo(tr);
		   			//单元
		   			var td2=$("<td class=\"tdborder3\"></td>");
		   			td2.appendTo(tr);

		   			//用户
		   			var td3 = $("<td class=\"tdborder2\" id='room"+data[i].SID+"'></td>");
		   			td3.appendTo(tr);

		   			var td4=$("<td class=\"tdborder4\" id='choseuser"+data[i].SID+"' >0个用户</td>");
		   			td4.appendTo(tr);

		   			if(width2 == 0){
			   			width2 = td2.outerWidth()-7;
			   			if(width2<240){
			   				width2 = 240;
				   		}
					}
		   			var select = $("<select name=\"unit"+data[i].SID+"\"  multiple='multiple' id=\"unit"+data[i].SID+"\"  class=\"form-control col-md-1\" style=\"width:"+width2+"px;\"></select>");
		   			select.appendTo(td2);
		   			var strBuffer = new StringBuffer(); 
		   			if(data[i].USID != null){
		   				var arrSid = data[i].USID;
						arrSid = arrSid.substring(0,arrSid.length-1).split(",");
						for (var j = 0; j < arrSid.length; j++) {
								var arrName = arrSid[j].split("|");
								strBuffer.append("<option value='");
								strBuffer.append(arrName[0]);
								strBuffer.append("'>");
								strBuffer.append(arrName[1]);
								strBuffer.append("</option>");
						}
					}
		   			if(strBuffer.toString() != ""){
		   				var option=$(strBuffer.toString());
						option.appendTo(select);
						var length = data[i].USID.split(",").length-1;
			   			$("#unit"+data[i].SID).multiselect({
			   				selectedText: '共'+length+'个单元，# 个被选中',
			   				ifChangeChoseRight:false,
			   				beforeclose: function(event, ui){
								var id = event.target.id;
								$("#"+id+"").multiselect("update");
			   					unitChangeSure(id);//根据单元查询所属用户
			   				},
				   				
				   		}).multiselectfilter();
					}else{
				   			$("#unit"+data[i].SID).multiselect({ 
				   				selectedText: '共0个单元，# 个被选中',
				   				ifChangeChoseRight:false,
				   				}).multiselectfilter();
					}
					

					
		   			if(width3 == 0){
			   			width3 = td3.outerWidth()-7;
			   			if(width3<302){
			   				width3 = 302;
				   		}
					}
		            var tdSelect=$("<select id='user"+data[i].SID+"' multiple='multiple' style='width:"+width3+"px;'></select>");
			   		tdSelect.appendTo($("#room"+data[i].SID));
		            var strBuffer = new StringBuffer(); 
		            var conut = 0;
					//存在
// 					if(data[i].USERIDS != null && typeof(data[i].USERIDS) != "undefined" ){
// 						var arrSid = data[i].USERIDS;
// 						arrSid = arrSid.substring(0,arrSid.length-1).split(",");
// 						var arrName = data[i].USERTEL;
// 						arrName = arrName.substring(0,arrName.length-1).split(",");
// 						var arrTel = data[i].USERNAME;
// 						arrTel = arrTel.substring(0,arrTel.length-1).split(",");
// 						for (var j = 0; j < arrSid.length; j++) {
// 							strBuffer.append("<option value='");
// 							strBuffer.append(arrSid[j]);
// 							strBuffer.append("'>");
// 							strBuffer.append(arrName[j]);
// 							strBuffer.append("  |  ");
// 							strBuffer.append(arrTel[j]);
// 							strBuffer.append("</option>");
// 						}
// 					}
					
					if(strBuffer.toString() != ""){
						var option=$(strBuffer.toString());
						option.appendTo(tdSelect);
						var userIdNow = $("#acceptUserId").val();
						var arr = intersection(data[i].USERIDS,userIdNow);
						var number = data[i].USERIDS.split(",").length;
						number = number-1;
						$("#user"+data[i].SID).val(arr);
				   			$("#user"+data[i].SID).multiselect({
				   				selectedText: '共'+number+'个用户，# 个被选中',
				   				ifChangeChoseRight:true,
				   				beforeclose: function(event, ui){
									var id = event.target.id;
									$("#"+id+"").multiselect("update");
									userSure(id);
				   				},
				   				}).multiselectfilter();
					}else{
				   			$("#user"+data[i].SID).multiselect({ 
				   				selectedText: '共0个用户，# 个被选中',
				   				ifChangeChoseRight:true,
				   				}).multiselectfilter();
					}
		   			
					
	            }
	        }, "json");
   }
    function changeUnit(unitid,sid) {
    	 if(unitid == '' || unitid ==null){
         	$("#user"+sid).multiselect({ 
    				selectedText: '共0个用户，# 个被选中',
    				ifChangeChoseRight:true,
    				}).multiselectfilter();
 				return;
         }
    	$.post("${pageContext.request.contextPath}/admin/croom_listRoom.action", {"unit": unitid,"sid":sid},function (data) {
    		 $("#room"+sid).empty();
    		 var width = $("#room"+sid).outerWidth()-7;
    		 var tdSelect=$("<select id='user"+sid+"' multiple='multiple' style='width:"+width+"px;'></select>");
 	   		tdSelect.appendTo($("#room"+sid));
            
            var strBuffer = new StringBuffer(); 
            var conut = 0;
			var useridAll = ",";
			for (var i = 0; i < data.length; i++) {
				//不存在或重复
				if(data[i].USERID == null || typeof(data[i].USERID) == "undefined" ){
					continue;
				}
				if(useridAll !="," && useridAll.indexOf(","+data[i].USERID+",") !=-1){
					continue;
				}
				conut ++;
				useridAll += data[i].USERID+",";
				strBuffer.append("<option value='");
				strBuffer.append(data[i].USERID);
				strBuffer.append("'>");
				strBuffer.append(data[i].USERNAME);
				strBuffer.append("  |  ");
				strBuffer.append(data[i].USERTEL);
				strBuffer.append("</option>");
			}
			if(strBuffer.toString() != ""){
				var option=$(strBuffer.toString());
				option.appendTo(tdSelect);
				
				useridAll = useridAll.substring(1,useridAll.length-1);
				$("#comuAlluser"+sid).val(useridAll);
				
				var userIdNow = $("#acceptUserId").val();
				var arr = intersection(useridAll,userIdNow);
				$("#user"+sid).val(arr);
		   			$("#user"+sid).multiselect({
		   				selectedText: '共'+conut+'个用户，# 个被选中',
		   				ifChangeChoseRight:true,
		   				beforeclose: function(event, ui){
							var id = event.target.id;
							$("#"+id+"").multiselect("update");
							userSure(id);
		   				},
		   				}).multiselectfilter();
			}else{
		   			$("#user"+sid).multiselect({ 
		   				selectedText: '共0个用户，# 个被选中',
		   				ifChangeChoseRight:true,
		   				}).multiselectfilter();
			}
        }, "json");
    }
  //查询单元下用户
    function unitChangeSure(id){
    	var unitid = $("#"+id+"").multiselect("MyValues");
    	var sid = id.substring(4);
    	changeUnit(unitid,sid);
    }
    function userSure(id){
    	// 更改用户，无操作
    	var userIdNow = $("#acceptUserId").val();
    	//去除本单元下所有的userid
    	var allComu = $("#comuAll"+id).val();
    	var newComu = offNoRepeat(allComu,userIdNow);
        //已选择选择的userId
	    var valuestr = $("#"+id+"").multiselect("MyValues"); 
	    if(valuestr ==''){
    		$("#acceptUserId").val(newComu);
        }else{
        	var newUserAdd = addNoRepeat(valuestr,newComu);
        	$("#acceptUserId").val(newComu+newUserAdd);
        }
    }
    
    function checkTail(){
    	if(!iffinish){
       	 layer.alert("请确认编辑完成");
       	 return;
       }
    	var tip="";
        var receiverId='';
        if(range==1){
			receiverId=$("#acceptUserId").val();
			if(receiverId=''){
				layer.alert("无法获取要发送的人员，请重新选择");
	        	return;
			}
			var count = receiverId.split(",").length-2;
			tip="本社区住户"+count+"个";
		}else{
			tip="本社区全部住户";
		}
        layer.confirm('确认发布公告？本次公告范围：'+tip, function (index) {
        	$("#sub").attr("disabled", "true");
    		var cmsg = UE.getEditor('editor').getContent();
    		var abstractMsg = removeHTMLTag(UE.getEditor('editor').getContent());
    		if(range==1){
    			receiverId=$("#acceptUserId").val();
    		}
    		$.post("${pageContext.request.contextPath}/admin/userMsg_add.action", {
    	    	'cMsg': cmsg,
    	    	'abstractMsg':abstractMsg,
    	    	'range':range,
    	    	'receiverId':receiverId
             }, function (result) {
                 result = JSON.parse(result)
                 if (result.code == 1) {
                	 window.location.href = "${pageContext.request.contextPath}/admin/userMsg_listNoticeView.action";
                 }else{
                	 $("#sub").removeAttr("disabled");
                 	layer.alert(result.msg);
                 }
             });
            
            layer.close(index);
        });
	}
    function cancel(){
    	window.location.href = "${pageContext.request.contextPath}/admin/userMsg_listNoticeView.action";
    }
    
    function getAllHtml() {
        alert(UE.getEditor('editor').getAllHtml());
    }
    function getContent() {
        var arr = [];
        arr.push("使用editor.getContent()方法可以获得编辑器的内容");
        arr.push("内容为：");
        arr.push(UE.getEditor('editor').getContent());
        alert(arr.join("\n"));
    }
    //完成
    function setDisabled() {
		if(UE.getEditor('editor').hasContents()){
	        UE.getEditor('editor').setDisabled('fullscreen');
	        disableBtn("enable");
	        $("#finish").attr("class","box5");
	        $("#finish").attr("disabled", "true");
	        $("#edit").attr("class","box4");
	        $("#edit").removeAttr("disabled");
	        iffinish=true;
	        $("#btns2").attr("style","");
			if(range==0){
				$("#sendAll").attr("disabled", "true");
		    	$("#sendAll").attr("class", "box5");
		    	$("#sendSingle").removeAttr("disabled");
		    	$("#sendSingle").attr("class", "box4");
		    	$("#mTypeDiv").attr("style","display:none");
			}else{
				$("#sendAll").removeAttr("disabled");
		    	$("#sendAll").attr("class", "box4");
		    	$("#sendSingle").attr("disabled", "true");
		    	$("#sendSingle").attr("class", "box5");
		    	$("#mTypeDiv").attr("style","");
		    	distribute();
			}
		}else{
			layer.alert("请输入内容");
		}
    }

    //修改
    function setEnabled() {
        UE.getEditor('editor').setEnabled();
        enableBtn();
        $("#finish").attr("class","box4");
        $("#finish").removeAttr("disabled");
        $("#edit").attr("class","box5");
        $("#edit").attr("disabled", "true");
        iffinish = false;
        $("#btns2").attr("style","display:none");
        $("#mTypeDiv").attr("style","display:none");
    }

   

    function getContentTxt() {
        var arr = [];
        arr.push("使用editor.getContentTxt()方法可以获得编辑器的纯文本内容");
        arr.push("编辑器的纯文本内容为：");
        arr.push(UE.getEditor('editor').getContentTxt());
        alert(arr.join("\n"));
    }
    function disableBtn(str) {
        var div = document.getElementById('btns');
        var btns = UE.dom.domUtils.getElementsByTagName(div, "button");
        for (var i = 0, btn; btn = btns[i++];) {
            if (btn.id == str) {
                UE.dom.domUtils.removeAttributes(btn, ["disabled"]);
            } else {
                btn.setAttribute("disabled", "true");
            }
        }
    }
    function enableBtn() {
        var div = document.getElementById('btns');
        var btns = UE.dom.domUtils.getElementsByTagName(div, "button");
        for (var i = 0, btn; btn = btns[i++];) {
            UE.dom.domUtils.removeAttributes(btn, ["disabled"]);
        }
    }
    function cancleMultiVulue(id){
    	$("#cancle"+id+"").click();
    }
    function ChangeChoseRightValue(id,chose){
	    $("#chose"+id+"").html(chose+"个用户");
    }
	function deleteMsg(sid){
		 layer.confirm('确认删除公告？用户消息中公告也将删除', function (index) {
             $.post("${pageContext.request.contextPath}/admin/userMsg_delete.action", {
                 "sid": sid
             }, function (result) {
            	 result = JSON.parse(result);
 	            if(result.code=='1'){
                	window.location.href = "${pageContext.request.contextPath}/admin/userMsg_listNoticeView.action";
 	          	}else{
 	          		layer.alert(result.msg);
 	           	}
             });
             layer.close(index);
         });
	}
	 function removeHTMLTag(str) {
         str = str.replace(/<\/?[^>]*>/g,''); //去除HTML tag
         str = str.replace(/[ | ]*\n/g,'\n'); //去除行尾空白
         //str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
         str=str.replace(/&nbsp;/ig,'');//去掉&nbsp;
         str=str.replace(/\s/g,''); //将空格去掉
         return str;
}
</script>
</body>
</html>
